package com.dingdang.controller;

import com.dingdang.data.Result;
import com.dingdang.em.ResultEnum;
import com.dingdang.entity.TbAdvertise;
import com.dingdang.mapper.TbAdvertiseMapper;
import com.dingdang.utils.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("advertise")
@Api(value = "广告推送,管理")
public class TestController {

    @Resource
    private TbAdvertiseMapper tbAdvertiseMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @GetMapping("get")
    @ApiOperation(value = "广告查询全部")
    public Result getInfo(HttpServletRequest request) {
        try {
            Map<String,Object> map = new HashMap<>();
            int status = 2;
            map.put("status",status);
            List<TbAdvertise> tbAdvertises = tbAdvertiseMapper.selectByMap(map);
            TbAdvertise tbAdvertise= (TbAdvertise) redisTemplate.boundValueOps("a").get();
            long time = tbAdvertise.getEndTime().getTime();
            Date date = new Date();
            long time1 = date.getTime();
            BigDecimal totalPrice = tbAdvertise.getTotalPrice();
            Integer price = Integer.valueOf(String.valueOf(totalPrice));
            if (time<time1 || price <=0){
                tbAdvertiseMapper.updateStatus(tbAdvertise.getId());
                MimeMessage message = javaMailSender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
                messageHelper.setSubject("请尽快续费,或者不再展示该广告");
                messageHelper.setText("<table border='1'>"+
                        "<p>该商家:"+tbAdvertise.getSellerName()+"</p>"+
                        "<p>"+"请尽快续费,若不续费自动下架该广告"+"</p>"+
                        "</table>", true);
                //收件人
                messageHelper.setTo(tbAdvertise.getEmail());
                //发件人
                messageHelper.setFrom(from);
                javaMailSender.send(message);
            }
            String ip = null;
            try {
                //以下两个获取在k8s中，将真实的客户端IP，放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
                ip = request.getHeader("authToken");
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
                }
                if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
                }
                if ("0:0:0:0:0:0:0:1".equals(ip)) {
                    ip = "127.0.0.1";
                }
                if (ip.split(",").length > 1) {
                    ip = ip.split(",")[0];
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.err.println(ip);
            redisTemplate.boundValueOps("ip").set(ip);
            redisTemplate.boundValueOps("ip").expire(30, TimeUnit.MINUTES);
            Object ip1 = redisTemplate.boundValueOps("ip").get();
            if (!ip.equals(ip1)){
                tbAdvertiseMapper.updateInfo();
            }
            return Result.ok().setData(tbAdvertises);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.response(ResultEnum.ERROR).setData(e);
        }
    }

    @PutMapping("add")
    @ApiOperation(value = "广告增加功能")
    @ApiImplicitParam(name = "tbAdvertise", value = "广告增加的实体类", required = true, paramType = "body")
    public Result addInfo(@RequestBody TbAdvertise tbAdvertise) {
        try {
            Integer f = tbAdvertise.getField();
            Map map1 = new HashMap<>();
            map1.put("field",f);
            List list = tbAdvertiseMapper.selectByMap(map1);
            if (list.size() !=0){
                return Result.ok().setData("该广告已经有排期");
            }else {
                Date startTime = tbAdvertise.getStartTime();
                Date endTime = tbAdvertise.getEndTime();
                Integer field = tbAdvertise.getField();
                Map<String, Object> map = new HashMap<>();
                if (field == 1) {
                    tbAdvertise.setTotalPrice(BigDecimal.valueOf(5000));
                } else if (field == 2) {
                    tbAdvertise.setTotalPrice(BigDecimal.valueOf(4000));
                } else if (field == 3) {
                    tbAdvertise.setTotalPrice(BigDecimal.valueOf(3000));
                } else if (field == 4) {
                    tbAdvertise.setTotalPrice(BigDecimal.valueOf(2000));
                } else if (field == 5) {
                    tbAdvertise.setTotalPrice(BigDecimal.valueOf(1000));
                }
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                map.put("field", field);
                tbAdvertise.setStatus(0);
                tbAdvertise.setOrderId(new IdWorker().nextId());
                tbAdvertiseMapper.insert(tbAdvertise);
                redisTemplate.boundValueOps("a").set(tbAdvertise);
                redisTemplate.expire("a",endTime.getTime(), TimeUnit.MINUTES);
                return Result.ok().setData(tbAdvertise.getOrderId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.response(ResultEnum.ERROR);
        }
    }

}
